import store from "../store";
import { USER_VALIDATE, ADD_ROUTE, CREATE_WEBSOCKET } from "../store/action.types";

const loginPermission = async function(to: any, _from: any, next: any) {
  const reuslt = await store.dispatch(`user/${USER_VALIDATE}`);
  const needLogin = to.matched.some((item: any) => item.meta.needLogin);
  const state: any = store.state;
  if (!state.user.hasPermission) {
    if (needLogin && !reuslt) {
      next("/login");
    }
    next();
  }else{
    next();
  }
  
};

const menuPermisson = async function(to: any, from: any, next: any) {
  const state: any = store.state;
  console.log('menuPermisson');
  if (state.user.hasPermission) {
    // 添加路由这里需要判断是否添加过路由了
    if (!state.user.menuPermission) {
      // 添加路由完成，但是是属于异步加载，不会立即更新
      store.dispatch(`user/${ADD_ROUTE}`);
      // replace 相当于replaceState替换掉并不进入历史记录 把路径添加完全
      next({ ...to, replace: true }); // 如果是next()时，进入到页面时报404.
    } else {
      next();
    }
  }else{
    next();
  }
  
};

const createWebSocket = async function(to: any, from: any, next: any) {
  const state: any = store.state;
  if(state.user.hasPermission && !state.state.ws){
    store.dispatch(`${CREATE_WEBSOCKET}`);
    next();
  }else{
    next();
  }
}


export default {
  loginPermission,
  menuPermisson,
  createWebSocket,
};
